package com.consumer.controller;


import com.consumer.lb.LoadBalancer;
import com.entities.Payment;
import com.entities.ResponseEntity;


import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;


import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @program: springcloud
 * @description:
 * @author: zfy
 * @create: 2020-08-16 10:08
 */
@Controller
@ResponseBody
public class ConsumerConroller {
//    访问固定端口
//    public static  final String PAYMENT_URL="http://localhost:8001/";
//    访问服务名称   需要开启负载均衡@LoadBalanced
    public static  final String PAYMENT_URL="http://CLOUD-PAYMENT-SERVICE/";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private LoadBalancer loadBalancer;

    @Resource
    private DiscoveryClient discoveryClient;
    @GetMapping("consumer/payment/lib")
    public String paymentLb(){
//        获取所有的服务实例集合
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (instances==null||instances.size()<=0){
            return null;
        }
//        获取提供服务的服务实例
        ServiceInstance instance = loadBalancer.instance(instances);
        URI uri = instance.getUri();

        return restTemplate.getForObject(uri+"/payment/lib",String.class);

    }


    @GetMapping("consumer/payment/insert")
    public ResponseEntity<Payment> creat(Payment payment){
        return restTemplate.postForObject(
                PAYMENT_URL+"payment/insert",
                payment,
                ResponseEntity.class);
    }
    @GetMapping("consumer/payment/select/{id}")
    public ResponseEntity<Payment> getPayment(@PathVariable("id") String id){
        return restTemplate.getForObject( PAYMENT_URL+"payment/select/"+id, ResponseEntity.class);

    }




}